// ProjectName: go-learn-demo
// PackageName: ybxblog
// Description:
// Author: hy.bai
// Date: 2025-08-13 星期三 13:53

package ybxblog

import (
	"errors"
	"fmt"
	"strings"
	"time"
)

type LogLevel uint16

// 日志常量
// 从低到高(详细程度递减)的顺序：TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
const (
	UNKNOW LogLevel = iota
	TRACE
	DEBUG
	INFO
	WARN
	ERROR
	OFF
)

// 解析日志级别
func paraLogLevel(level string) (LogLevel, error) {
	level = strings.ToLower(level) // 转换为小写
	switch level {
	case "trace":
		return TRACE, nil
	case "debug":
		return DEBUG, nil
	case "info":
		return INFO, nil
	case "warn":
		return WARN, nil
	case "error":
		return ERROR, nil
	case "off":
		return OFF, nil
	default:
		err := errors.New("无效的日志级别")
		return UNKNOW, err
	}
}

// 日志对象
type Logger struct {
	Level LogLevel
}

// 根据日志级别返回日志对象
func NewCustomLogger(logLevel string) *Logger {
	level, err := paraLogLevel(logLevel)
	if err != nil {
		panic(err)
	}
	return &Logger{Level: level}
}

// 是否能够打印某个级别的日志
func (l *Logger) enable(level LogLevel) bool {
	return level >= l.Level
}

// trace级别
func (l *Logger) Trace(msg string) {
	if l.enable(TRACE) {
		fmt.Printf("%s [TRACE] %s\n", time.Now().Format(time.DateTime), msg)
	}
}

// debug级别
func (l *Logger) Debug(msg string) {
	if l.enable(DEBUG) {
		fmt.Printf("%s [DEBUG] %s\n", time.Now().Format(time.DateTime), msg)
	}
}

// Info级别
func (l *Logger) Info(msg string) {
	if l.enable(INFO) {
		fmt.Printf("%s [INFO] %s\n", time.Now().Format(time.DateTime), msg)
	}
}

// Warnig级别
func (l *Logger) Warn(msg string) {
	if l.enable(WARN) {
		fmt.Printf("%s [WARN] %s\n", time.Now().Format(time.DateTime), msg)
	}
}

// Error级别
func (l *Logger) Error(msg string) {
	if l.enable(ERROR) {
		fmt.Printf("%s [ERROR] %s\n", time.Now().Format(time.DateTime), msg)
	}
}

// Off级别
func (l *Logger) Off(msg string) {
	if l.enable(OFF) {
		// 注意：Off级别不打印日志
		// fmt.Printf("%s [Off] %s\n", time.Now().Format(time.DateTime), msg)
	}
}
